package com.vms.gsmchecker;

import vms.data.CheckerJob;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.vms.data.CheckerLocation;
import com.vms.data.GSMNetworkInfo;

public class GSMCheckerActivity extends Activity implements OnTouchListener {
	public static final int MENU_SETTING = 1;
	public static final int MENU_ABOUT = 2;
	public static final int MENU_HELP = 3;

	public GSMNetworkInfo mGSMNetworkInfo;
	public CheckerLocation mCheckLocation;

	private CheckerJob checkerjob;
	private Updater updater;

	Button btStart;
	Button btReport;

	TextView textViewOperator;
	TextView textViewMCCMNC;
	TextView textViewTechnology;
	TextView textViewSignal;
	TextView textViewLAC;
	TextView textViewCellID;
	TextView textViewRoaming;
	TextView textViewBitErrorRate;
	TextView textViewEDVO;
	TextView textViewECIO;
	TextView textViewSNR;
	TextView textViewNeighbourCells;
	TextView textViewLatitude;
	TextView textViewLongitude;
	TextView textViewManufacture;
	TextView textViewModel;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main_report);
		mGSMNetworkInfo = GSMNetworkInfo.getInstance((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
		mCheckLocation = CheckerLocation.getInstance((LocationManager) getSystemService(Context.LOCATION_SERVICE));

		btStart = (Button) findViewById(R.id.btStart);
		btReport = (Button) findViewById(R.id.btReport);
		btStart.setOnTouchListener(this);
		btReport.setOnTouchListener(this);

		textViewOperator = (TextView) findViewById(R.id.textViewOperator);
		textViewMCCMNC = (TextView) findViewById(R.id.textViewMCCMCC);
		textViewTechnology = (TextView) findViewById(R.id.textViewTechnology);
		textViewSignal = (TextView) findViewById(R.id.textViewSignal);
		textViewLAC = (TextView) findViewById(R.id.textViewLAC);
		textViewCellID = (TextView) findViewById(R.id.textViewCellID);
		textViewRoaming = (TextView) findViewById(R.id.textViewRoaming);
		textViewLatitude = (TextView) findViewById(R.id.textViewLatitude);
		textViewLongitude = (TextView) findViewById(R.id.textViewLongitude);
		textViewManufacture = (TextView) findViewById(R.id.textViewManufacture);
		textViewModel = (TextView) findViewById(R.id.textViewModel);

		textViewBitErrorRate = (TextView) findViewById(R.id.textViewBitErrorRate);
		textViewEDVO = (TextView) findViewById(R.id.textViewEVDO);
		textViewECIO = (TextView) findViewById(R.id.textViewECIO);
		textViewSNR = (TextView) findViewById(R.id.textViewSNR);
		textViewNeighbourCells = (TextView) findViewById(R.id.textViewNeighBourCells);
		
		textViewManufacture.setText(Build.MANUFACTURER);
		textViewModel.setText(Build.MODEL);
		
		updater = new Updater(this);
		updater.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(updater != null){
			updater.stopUpdater();
			updater = null;
		}
	}
	@Override
	protected void onPause() {
		super.onPause();
		if(updater != null){
			updater.stopUpdater();
			updater = null;
		}
	}
	@Override
	protected void onResume() {
		super.onResume();
		mGSMNetworkInfo = GSMNetworkInfo.getInstance((TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE));
		mCheckLocation = CheckerLocation.getInstance((LocationManager) getSystemService(Context.LOCATION_SERVICE));
		
		updater = new Updater(this);
		updater.start();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(1, MENU_SETTING, MENU_SETTING, "Settings");
		menu.add(1, MENU_ABOUT, MENU_ABOUT, "About");
		menu.add(1, MENU_HELP, MENU_HELP, "Help");
		// TODO Auto-generated method stub
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case MENU_SETTING:
			viewSettings();
			return true;
		case MENU_ABOUT:
			viewText(item.getItemId());
			return true;
		case MENU_HELP:
			viewText(item.getItemId());
			return true;

		}
		return super.onOptionsItemSelected(item);
	}

	private void viewSettings() {
		// TODO Auto-generated method stub

	}

	public void viewText(long id) {

		Intent intent = new Intent(GSMCheckerActivity.this, HelpActivity.class);
		intent.putExtra("id", (int) id);

		if (id == MENU_HELP) {
			intent.putExtra("title", "Help");
		} else
			intent.putExtra("title", "About");

		startActivity(intent);
	}

	public void updateData() {
		Handler refresh = new Handler(Looper.getMainLooper());
		refresh.post(new Runnable() {
			public void run() {

				int cid = GSMNetworkInfo.getInstance(null).getCellID();
				int lac = GSMNetworkInfo.getInstance(null).getLAC();
				String networkOperator = GSMNetworkInfo.getInstance(null).getNetworkOperator();
				int signalStrengt = GSMNetworkInfo.getInstance(null).getSignalStreght();
				double latitude = mCheckLocation.getLatitude();
				double longitude = mCheckLocation.getLongitude();

				textViewCellID.setText("" + cid);
				textViewLAC.setText("" + lac);
				textViewOperator.setText(networkOperator);
				textViewMCCMNC.setText(GSMNetworkInfo.getInstance(null).getMCC() + " - " + GSMNetworkInfo.getInstance(null).getMNC());
				textViewTechnology.setText(GSMNetworkInfo.getInstance(null).getNetworkType());
				textViewSignal.setText("" + signalStrengt + " dBm");
				textViewRoaming.setText(GSMNetworkInfo.getInstance(null).isRoaming() ? "Roaming" : "Home");
				textViewBitErrorRate.setText(GSMNetworkInfo.getInstance(null).getBitErrorRate());
				textViewEDVO.setText(GSMNetworkInfo.getInstance(null).getEVDO());
				textViewECIO.setText(GSMNetworkInfo.getInstance(null).getECIO());
				textViewSNR.setText(GSMNetworkInfo.getInstance(null).getSNR());
				textViewNeighbourCells.setText(GSMNetworkInfo.getInstance(null).getNeighbourCells());
				textViewLatitude.setText("" + latitude);
				textViewLongitude.setText("" + longitude);
			}
		});

	}

	public boolean onTouch(View button, MotionEvent event) {
		Log.i("INFO", "Button Click");
		if (button == btStart) {
			if (event.getAction() == MotionEvent.ACTION_UP) {
				if (checkerjob == null) {
					checkerjob = new CheckerJob();
				}
				if (!checkerjob.isRunning()) {
					checkerjob.start();
					Handler refresh = new Handler(Looper.getMainLooper());
					refresh.post(new Runnable() {
						public void run() {
							btStart.setText("   Stop   ");
							
							Toast toast = Toast.makeText(getApplicationContext(),"Data collection has started! Click stop button to stop.",Toast.LENGTH_LONG);
							toast.show();
						}
					});

				} else {
					checkerjob.stopCheckJob();
					checkerjob = null;

					Handler refresh = new Handler(Looper.getMainLooper());
					refresh.post(new Runnable() {
						public void run() {
							btStart.setText("  Start  ");
							Toast toast = Toast.makeText(getApplicationContext(),"Data collection stopped!",Toast.LENGTH_LONG);
							toast.show();
						}
					});
				}
			}

			return true;
		} 
		
		if(button == btReport){
			Intent intent = new Intent(GSMCheckerActivity.this, ReportActivity.class);
			startActivity(intent);
		}

		return false;
	}
}

class Updater extends Thread {
	GSMCheckerActivity listener;
	private boolean stop;

	public Updater(GSMCheckerActivity home) {
		this.listener = home;
	}

	public void run() {
		while (!stop) {
			listener.updateData();
			Thread.yield();
			try {
				Thread.sleep(2000l);
			} catch (Exception e) {
				// TODO: handle exception
			}
		}
	}

	public void stopUpdater() {
		this.stop = true;
	}
}